<?php
/**
 * Created by PhpStorm.
 * User: wiggin
 * Date: 2017/11/3
 */

namespace App\Model;

use App\Utility\Db\Redis;

class Queue
{
    const QUEUE_NAME = 'wait_task_list';
    const QUEUE_RUNNING_NAME = 'running_task_list';

    public static function getTaskNum()
    {
        return Redis::getInstance()->hLen(self::QUEUE_NAME);
    }

    public static function isRunning($key)
    {
        $redis = Redis::getInstance();
        return $redis->hExists(self::QUEUE_NAME, $key) || $redis->hExists(self::QUEUE_RUNNING_NAME, $key);
    }

    public static function setTask($key, $data)
    {
        $redis = Redis::getInstance();
        //没有在等待的任务队列中且同时也不在正在运行的队列中
        if (!$redis->hExists(self::QUEUE_NAME, $key) && !$redis->hExists(self::QUEUE_RUNNING_NAME, $key)) {
            return $redis->hSet(self::QUEUE_NAME, $key, $data);
        }
        return false;
    }

    public static function getTask($key, $taskId)
    {
        if (empty($key) || $taskId < 0) {
            return false;
        }
        $redis = Redis::getInstance();
        $data = $redis->hGet(self::QUEUE_NAME, $key);
        $redis->transaction();
        $redis->hDel(self::QUEUE_NAME, $key);
        $redis->hSet(self::QUEUE_RUNNING_NAME, $key, $taskId);
        $flag = $redis->redisExec();
        if ($flag) {
            return $data;
        }
        return false;
    }

    public static function getTaskList()
    {
        return Redis::getInstance()->hKeys(self::QUEUE_NAME);
    }

    public static function endTask($taskId)
    {
        $redis = Redis::getInstance();
        $runList = $redis->hGetAll(self::QUEUE_RUNNING_NAME);
        if ($runList) {
            $key = array_search($taskId, $runList);
            if ($key) {
                return Redis::getInstance()->hDel(self::QUEUE_RUNNING_NAME, $key);
            }
        }
        return false;
    }
}